package com.example.chatroom.controller;

import com.example.chatroom.mapper.UserMapper;
import com.example.chatroom.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 均先生
 * Date: 2024-03-06
 * Time: 19:17
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    // TODO: 2024-03-06 19:18

    @RequestMapping("/register")
    public Object register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        if (userMapper.selectUserByUsername(username) != null) {
            log.info("用户名已存在!");
            return new User();
        }

        int i = userMapper.insertUser(user);
        if (i > 0) {
            log.info("注册成功!");
            return user;
        }
        log.info("注册失败!");
        return new User();
    }

    @ResponseBody
    @RequestMapping("/login")

    public Object login( String username,  String password, HttpServletRequest request,
                      HttpServletResponse response) {
        User user = userMapper.selectUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            log.info("登录失败!");
            return new User();
        }
        //登录成功,创建会话
        request.getSession().setAttribute("user", user);
        return user;

    }

}
